import 'package:fish_redux/fish_redux.dart';
import 'action.dart';
import 'state.dart';
import '../../../app_files.dart';
import 'package:month_picker_dialog/month_picker_dialog.dart';

Effect<OrderListViewState> buildEffect() {
  return combineEffects(<Object, Effect<OrderListViewState>>{
    OrderListViewAction.onTapTime: _onTapTime,
    OrderListViewAction.onLoad: _onLoad,
    Lifecycle.initState: _initState,
    Lifecycle.dispose: _dispose,
  });
}

void _dispose(Action action, Context<OrderListViewState> ctx) async {
  bus.off('refreshOrderList');
}

void _initState(Action action, Context<OrderListViewState> ctx) async {
  _sendRequest(ctx, 1);
  bus.on('refreshOrderList', (arg) {
    _sendRequest(ctx, 1);
  });
}

void _onTapTime(Action action, Context<OrderListViewState> ctx) async {
  ctx.state.selectTime = await showMonthPicker(
    context: ctx.context,
    firstDate: DateTime(1990),
    lastDate: DateTime.now(),
    initialDate: ctx.state.selectTime ?? DateTime.now(),
    locale: Locale("zh"),
  );
  ctx.state.items = null;
  ctx.dispatch(OrderListViewActionCreator.onAction());
  _sendRequest(ctx, 1);
}

_sendRequest(Context<OrderListViewState> ctx, int page) async {
  ResultData res = await CommonNetWork.orderList(
    orderTime: ctx.state.selectTime == null
        ? ''
        : '${ctx.state.selectTime.year}-${ctx.state.selectTime.month}',
    page: page,
  );
  if (res.success) {
    List data = res.data ?? [];
    List item = data.map((e) => OrderListItemModel.fromJson(e)).toList();
    ctx.dispatch(
        OrderListViewActionCreator.onGetData({'items': item, 'page': page}));
  } else {
    CommonUtils.showErrorInfo(ctx.context, res.desc);
  }
}

void _onLoad(Action action, Context<OrderListViewState> ctx) async {
  await _sendRequest(ctx, action.payload);
}
